//
//  BQRefreshControl.swift
//  BQWB
//
//  Created by laibingqiang on 16/10/30.
//  Copyright © 2016年 laibingqiang. All rights reserved.
//

import UIKit

enum refreshtype:Int {
    //下拉
    case refreshxiaLa
    //上
    case refreshshangLa
    //刷新状态
    case refreshing
}

class BQRefreshControl: UIControl {
    //KVO监听的对象
    var myScrollView:UIScrollView?
    //定义枚举属性
    var isRefresh:refreshtype = .refreshxiaLa{
        //实时监听
        didSet{
            
            switch isRefresh {
            case .refreshxiaLa:
                jianTouImgV.isHidden = false
                juHua.stopAnimating()
                UIView.animate(withDuration: 0.24, animations: { 
                    self.jianTouImgV.transform = CGAffineTransform.identity
                    self.myScrollView?.contentInset.top = 64
                })
                messageL.text = "下拉刷新"
                
            
            case .refreshshangLa:
                
                UIView.animate(withDuration: 0.25, animations: { 
                    self.jianTouImgV.transform = CGAffineTransform((rotationAngle: CGFloat(M_PI)))
                })
                
                messageL.text = "松手进入刷新"
                
            case .refreshing:
                jianTouImgV.isHidden = true
                messageL.text = "正在刷新"
                juHua.startAnimating()
                UIView.animate(withDuration: 0.25, animations: { 
                    
                    self.myScrollView?.contentInset.top = 128

                })
                
                sendActions(for: UIControlEvents.valueChanged)
                
            }
        }
    }
    //移除kVO
    deinit {
        
        myScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    func endRefreshing(){
        
        
        isRefresh = .refreshxiaLa
    }

    override init(frame: CGRect) {
        
        let screenW:CGFloat = UIScreen.main.bounds.size.width
        super.init(frame: CGRect(x: 0, y: -64, width: screenW, height: 64))
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置视图
    private func setupUI(){
        
        self.backgroundColor = UIColor.blue
        //添加子控件
        addSubview(jianTouImgV)
        addSubview(messageL)
        addSubview(juHua)
        //原生约束
        jianTouImgV.translatesAutoresizingMaskIntoConstraints = false
        messageL.translatesAutoresizingMaskIntoConstraints = false
        juHua.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: jianTouImgV, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: jianTouImgV, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageL, attribute: .leading, relatedBy: .equal, toItem: jianTouImgV, attribute: .trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageL, attribute: .centerY, relatedBy: .equal, toItem: jianTouImgV, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: juHua, attribute: .centerX, relatedBy: .equal, toItem: jianTouImgV, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: juHua, attribute: .centerY, relatedBy: .equal, toItem: jianTouImgV, attribute: .centerY, multiplier: 1, constant: 0))
        
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        if let scrollView = newSuperview as? UIScrollView{
            myScrollView = scrollView
            //KVO动态监听父控件中的属性
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let scrollView = myScrollView else {
            return
        }
        
        let maxY:CGFloat = -(scrollView.contentInset.top + 64)
        
        //print(scrollView.contentOffset.y,scrollView.contentInset.top)
        
        
        if scrollView.isDragging{
            if scrollView.contentOffset.y >= maxY && self.isRefresh == refreshtype.refreshshangLa{
                
                self.isRefresh = refreshtype.refreshxiaLa
            }
            
            if scrollView.contentOffset.y < maxY && self.isRefresh == refreshtype.refreshxiaLa{
                
                self.isRefresh = refreshtype.refreshshangLa
            }
        }
        else
        {
            if scrollView.contentOffset.y < maxY{
                
                self.isRefresh = refreshtype.refreshing
            }
        }
    }
    //箭头
    private var jianTouImgV:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //提示文字
    private var messageL:UILabel = {
        let l = UILabel()
        l.textColor = UIColor.red
        l.font = UIFont.systemFont(ofSize: 11)
        l.textAlignment = .center
        l.text = "下拉刷新"
        
        return l
        
    }()
    //菊花
    private var juHua:UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        view.color = UIColor.green
        
        return view
        
    }()
}
